const tableEle = document.querySelector('table')
console.log(tableEle);
let cartListStr = localStorage.getItem('DS-CART-LIST')
let cartList = JSON.parse(cartListStr) || []
let stateAll = false


/**
 * 动态渲染购物车
 */
function showCartList() {
    let trStr = cartList.map(item => {
        return `    
                    <tr>
					<td><input type="checkbox" name="checksingle" ${item.state ? 'checked' : ''} data-index="${item.id}"></td>
                    <td><img src="${item.url}" alt="p2" /></td>
                    <td>${item.name}</td>
                    <td>￥${item.price}</td>
                    <td class="active">
                        <input type="button" value="-" name="minus" data-index="${item.id}" ${item.num == 0 ? 'disabled' : '0'} />
                        <input type="text" value="${item.num}" name="amount" />
                        <input type="button" value="+" name="plus" data-index="${item.id}"/>
                    </td>
                    <td class="all-price">￥${(item.num * item.price).toFixed(2)}</td>
                    <td>
                        <a href="#">移入收藏</a><br />
                        <a href="#" class="del" data-index="${item.id}">删除</a>
                    </td>
                </tr>`
    }).join('')

    let thStr = `<tr>
                <th><input type="checkbox" name="checkall" ${stateAll ? 'checked' : ''}>全选</th>
                <th>商品图片</th>
                <th width="300px">商品信息</th>
                <th>单价</th>
                <th>数量</th>
                <th width="100px">总价</th>
                <th>操作</th>
            </tr>`
    thStr += trStr

    tableEle.innerHTML = thStr

}

/*
   操作商品
 */
function onProduct() {
    /*
         删除
    */
    tableEle.addEventListener('click', function (e) {
        e = e || window.event
        let target = e.target || e.srcElement
        if (target.getAttribute('class') == 'del') {
            let id = target.getAttribute('data-index')
            // console.log('>>>' + id);
            // console.log('cartList' + cartList);
            let index = cartList.findIndex(item => item.id == id)
            cartList.splice(index, 1)
            showCartList()
            onTotalPrice()
        }

        /*
             加一
        */
        if (target.getAttribute('value') == '+') {
            let id = target.getAttribute('data-index')
            let product = cartList.find(item => item.id == id)
            // console.log('product'+product);
            product.num++
            product.singlePrice = (product.num * product.price).toFixed(2)
            showCartList()
            onTotalPrice()

        }
        /**
         * 减操作
         */
        if (target.getAttribute('value') == '-') {
            //获取id
            let id = target.getAttribute('data-index')
            //查找商品
            let product = cartList.find(item => item.id == id)

            //数量减一
            product.num--
            if (product.num < 0) {
                product.num = 0
            }
            //计算价格
            product.singlePrice = (product.num * product.price).toFixed(2)
            showCartList()
            onTotalPrice()
        }

        /*
             全选功能
        */
        if (target.getAttribute('name') == 'checkall') {
            stateAll = !stateAll
            cartList.forEach(item => (item.state = stateAll))

            //全选商品计算商品总价
            let total = 0
            const allPrice = document.querySelectorAll('.all-price')
            for (let i = 0; i < allPrice.length; i++) {
                total += Number(allPrice[i].innerHTML.substring(1))
            }
            if (stateAll == false) {
                totalPriceEle[0].innerHTML = `￥0`;
                totalPriceEle[1].innerHTML = `￥0`;
            } else {
                totalPriceEle[0].innerHTML = `￥${total}`;
                totalPriceEle[1].innerHTML = `￥${total}`;
            }
            
        
            
            console.log(total);

            showCartList()

        }

        /*
            单选功能
         */
        if (target.getAttribute('name') == 'checksingle') {
            let id = target.getAttribute('data-index')
            let product = cartList.find(item => item.id == id)
            product.state = !product.state
            product.singlePrice = (product.num * product.price).toFixed(2)
            let sum = Number(product.singlePrice)
            if (product.state == true) {
                onTotalPrice()

            } else {
                product.singlePrice = -(product.num * product.price).toFixed(2)
                console.log( product.singlePrice);
                onTotalPrice()

            }
            stateAll = cartList.every(item => item.state == true)
            showCartList()
        }
    })
}



//显示总价
const totalPriceEle = document.querySelectorAll('.total-price>span')
console.log(totalPriceEle);


function onTotalPrice() {
    let sum = 0
    console.log(cartList);
    for (let i = 0; i < cartList.length; i++) {
        if (cartList[i].state == true) {
            // console.log(cartList[i].singlePrice);
            let singlePrice = cartList[i].singlePrice
            // console.log('>>' + singlePrice);
            sum += Number(singlePrice)
        }

    }



    totalPriceEle[0].innerHTML = `￥${sum.toFixed(2)}`
    totalPriceEle[1].innerHTML = `￥${sum.toFixed(2)}`



}



/*
     获取m-n之间的随机数
*/
function getRandom(m, n) {
    var max = Math.max(m, n)
    var min = Math.min(m, n)
    return Math.floor(Math.random() * (max - min) + min)
}
showCartList()
onProduct()
onTotalPrice()